<template>
    <el-row style="height: 3vh;">
        {{ props.shareName + "的共享桌面" }}
        <el-button style="margin-left: 10px;margin-top: -5px;" v-show="showButton" type="primary" @click="stopShare"
            plain>{{ buttonName }}</el-button>
    </el-row>
    <el-row style="width: 100%;height: 91vh;">
        <el-col style="width: 85%;max-width: 85%;">
            <video ref="videos" style="width: 100%;height: 100%;" controls></video>
        </el-col>
        <el-col style="width: 15%;max-width: 15%;">
            <el-card style="height: 100%;">
                <template #header>
                    <div class="card-header">
                        <span>参与人</span>
                    </div>
                </template>
                <el-menu>
                    <el-menu-item v-for="(item, index) in userData" :key="index">{{ item.name }}
                        <audio :id="item.id" ref="audio" :autoplay="false">

                        </audio>
                        <div :id="item.id + 'processbar'"
                            style="width: 0; height: 20px; background-color: #4caf50;margin-top: 0px;margin-left: 10px;">
                        </div>
                    </el-menu-item>
                </el-menu>
            </el-card>
        </el-col>
    </el-row>
</template>
<script>
import { ref, onMounted, onUnmounted } from 'vue';
import { videoStore } from '@/store/video'
import { SignalrStore } from '@/store/signalrStore'
export default {
    props: {
        shareName: String
    },
    setup(props) {
        var videos = ref();
        var urlData = null;
        var mapSdk = new Map();
        var showButton = ref(false);
        var mapchatSdk = new Map();
        var allUser = ref([]);
        var audio = ref();
        var userData = ref([]);
        var buttonName = ref("停止共享")
        var shareModel = null;
        onUnmounted(() => {
            setTimeout(() => {
                mapSdk.forEach((value, key) => {

                    console.log('close');
                    value.stream.getTracks().forEach(track => {
                        track.stop(); // 停止轨道传输
                    });
                    value.close();
                    value = null;
                });
                mapSdk = new Map();
                mapchatSdk.forEach((value, key) => {

                    console.log('close');
                    value.stream.getTracks().forEach(track => {
                        track.stop(); // 停止轨道传输
                    });
                    value.close();
                    value = null;
                });
                mapchatSdk = new Map();
            }, 400)
        });
        const stopShare = async () => {
            if (buttonName.value == "停止共享") {
                var shareUser = await fetch(urlData.apiUrl + "/StopShare?Name=" + props.shareName);
                mapSdk.forEach((value, key) => {
                    var name = videoStore().getName();
                    if (key == name) {
                        console.log('close');
                        value.stream.getTracks().forEach(track => {
                            track.stop(); // 停止轨道传输
                        });
                        value.close();
                        value = null;

                    }
                    videos.value.srcObject = null;
                    buttonName.value = "共享桌面";
                });
            }
            else
            {
                mapSdk.forEach((value, key) => {
                    var name = videoStore().getName();
                    if (key == name&&value!=null) {
                        console.log('close');
                        value.stream.getTracks().forEach(track => {
                            track.stop(); // 停止轨道传输
                        });
                        value.close();
                        value = null;

                    }
                    videos.value.srcObject = null;
                });
                buttonName.value = "停止共享";
                pullDisplay();
            }
        };
        onMounted(async () => {
            var res = await fetch('/configjs.json?d=' + new Date());
            urlData = await res.json();
            var time=new Date().getTime();
            setTimeout(async () => {
                var id = videoStore().getId();
                var shareUser = await fetch(urlData.apiUrl + "/GetShareUser?Name=" + props.shareName);
                shareModel = await shareUser.json();
                userData.value = shareModel.allUsers;
                if (id == shareModel.id) {

                    pullDisplay();
                    showButton.value = true;
                }
                pullAudio();

            }, 100)
            SignalrStore().getSignalrInstance().on("Notity", (datas) => {
                if (datas && datas.length > 0) {
                    // mapchatSdk.forEach((value, key) => {

                    //     console.log('close');
                    //     value.stream.getTracks().forEach(track => {
                    //         track.stop(); // 停止轨道传输
                    //     });
                    //     value.close();
                    //     value = null;
                    // });
                    datas.forEach(element => {
                        if (element.stream.includes("Audio")) {
                            var currentname = videoStore().getName();
                            var name = element.app.replace("share", "");
                            if (name != currentname) {
                                play(element);
                            }
                        }
                        else {
                            if (videos.value.srcObject == null) {
                                console.log(11222333);
                                play(element);
                            }
                            var currentname = videoStore().getName();
                            var name = element.app.replace("share", "");
                            if(name!=currentname)
                            {
                                showButton.value=false;
                            }
                        }

                    });
                }
                console.log(datas);
            });
            SignalrStore().getSignalrInstance().on("ShareInsertUser", (datas) => {
                userData.value = datas.allUsers;
                console.log(datas);
            });
            SignalrStore().getSignalrInstance().on("StopShare", (datas) => {
                mapchatSdk.forEach((value, key) => {
                    if (key == videoStore().getName()) {

                        console.log('close StopShare');
                        value.stream.getTracks().forEach(track => {
                            track.stop(); // 停止轨道传输
                        });
                        value.close();
                        value = null;
                    }
                });
                if (!showButton.value) {
                    showButton.value = true;
                }
                buttonName.value = "共享桌面";
                videos.value.srcObject = null;
            });
        });
        const pullDisplay = async () => {

            var audio = videoStore().getAudio();
            var video = videoStore().getVideo();
            var name = videoStore().getName();
            var sdks = new SrsRtcWhipWhepAsync(video, audio, true);
            var Finalurl = urlData.pushUrl + 'app=share' + name + '&stream=' + props.shareName;
            await sdks.publish(Finalurl);
            mapSdk.set(name, sdks);
        }
        const pullAudio = async () => {
            var audio = videoStore().getAudio();
            var name = videoStore().getName();
            console.log(audio);
            if (audio != "" && audio != '') {
                var sdks = new SrsRtcWhipWhepAsync('', audio);
                var Finalurl = urlData.pushUrl + 'app=share' + name + '&stream=Audio' + props.shareName;
                await sdks.publish(Finalurl);
                mapSdk.set(name + "audio", sdks);
            }
            else {
                var streamData = shareModel.requestDatas.filter(s => s.stream == props.shareName);
                if (streamData && streamData.length > 0) {
                    play(streamData[0]);
                }
            }
        }

        const play = async (item) => {
            var name = videoStore().getName();
            var url = urlData.pullUrl + "app=" + item.app + '&stream=' + item.stream + ".flv";
            var r = apply_url_change(url);
            var sdk = new SrsRtcWhipWhepAsync();
            if (item.stream.includes("Audio")) {
                var user = userData.value.filter(s => s.name == item.app.replace("share", ""))
                if (user && user.length > 0) {
                    var audioElement = document.getElementById(user[0].id);
                    audioElement.srcObject = sdk.stream;
                }
            }
            else {

                videos.value.srcObject = sdk.stream;
            }
            await sdk.play(r.url, {
                videoOnly: false,
                audioOnly: false,
            });
            if (item.stream.includes("Audio")) {
                var user = userData.value.filter(s => s.name == item.app.replace("share", ""))
                if (user && user.length > 0) {
                    var audioElement = document.getElementById(user[0].id);
                    audioElement.srcObject = sdk.stream;
                    var audioContext = new AudioContext();
                    var analyser = audioContext.createAnalyser();
                    // 获取音频流源
                    var source = audioContext.createMediaStreamSource(sdk.stream);
                    source.connect(analyser);

                    // 设置音频分析器
                    analyser.fftSize = 256;
                    var bufferLength = analyser.frequencyBinCount;
                    var dataArray = new Uint8Array(bufferLength);

                    // 获取声音大小并更新进度条
                    function updateProgress() {
                        analyser.getByteFrequencyData(dataArray);
                        var total = 0;
                        for (var i = 0; i < bufferLength; i++) {
                            total += dataArray[i];
                        }
                        var average = total / bufferLength;
                        var progressBar = document.getElementById(user[0].id + 'processbar');
                        progressBar.style.width = average + 'px';

                        requestAnimationFrame(updateProgress);
                    }
                    // 开始更新进度条
                    updateProgress();
                    audioElement.play();
                }

                mapchatSdk.set(name + "Audio", sdk);
            }
            else {

                videos.value.play();
                mapchatSdk.set(name, sdk);
            }
        }
        var apply_url_change = function (url) {
            var query = parse_query_string();
            var r = parse_rtmp_url(url);
            var url = window.location.protocol + "//" + query.host + query.pathname + "?autostart=true"
                + "&app=" + r.app + "&stream=" + r.stream + "&server=" + r.server + "&port=" + r.port;
            url += (query.shp_identify) ? "&shp_identify=" + query.shp_identify : '';
            url += (r.vhost === "__defaultVhost__") ? "&vhost=" + r.server : "&vhost=" + r.vhost;
            url += (r.schema !== "rtmp") ? "&schema=" + r.schema : '';
            url += (query.buffer) ? "&buffer=" + query.buffer : '';
            url += (query.api_port) ? "&api_port=" + query.api_port : '';

            var queries = user_extra_params(query);
            queries = user_extra_params(r, queries);

            if (queries && queries.length) {
                url += '&' + queries.join('&');
            }

            return r;
        };
        const calcel = () => {
            if (sdk) {
                console.log(111);
                sdk.close();
            }
        }
        window.addEventListener('unload', function (event) {
            calcel();
        });
        return {
            videos, props, audio, userData, stopShare, showButton, buttonName
        };
    }
}
</script>